<?php /** @noinspection ALL */


namespace app\admin\controller;


use think\facade\Db;

class OptionType {

	function edit(){
		$input=input();

		if (empty($input['name'])) return json(['code' => 0, 'msg' => '请输入分类标题']);

		if ($input['is_show']=='') return json(['code' => 0, 'msg' => '请选择是否显示']);

		if ($input['status']=='') return json(['code' => 0, 'msg' => '请选择状态']);

		if ($input['sort']=='') return json(['code' => 0, 'msg' => '请输入排序']);

		$data=[
			'name'=>$input['name'],
			'add_time'=>time(),
			'sort'=>$input['sort']!=''?$input['sort']:0,
			'is_show'=>$input['is_show']!=''?$input['is_show']:0,
			'status'=>$input['status']!=''?$input['status']:0,
		];

		if(empty($input['id'])){

			$option_type=db::name('option_type')->insert($data);

			if (!$option_type){
				return json(['code'=>0,'msg'=>'编辑失败']);
			}
		}else{

			$option_type=db::name('option_type')->where('id',$input['id'])->update($data);

			if (!$option_type){
				return json(['code'=>0,'msg'=>'编辑失败']);
			}
		}
		return json(['code'=>1,'msg'=>'编辑成功']);
	}

	function show($page=1,$pageSize=10){

		$input=input();

		$condition = ' and 1=1';

		if (!empty($input['name'])) {
			$input['name']=trim($input['name']);
			$condition .= " and name like '%{$input['name']}%' ";
		}

		$list = Db::query("select *,FROM_UNIXTIME(add_time,'%Y-%m-%d %H:%i:%s')  as add_time from option_type where 1".$condition." order by id desc limit ".(($page-1)*$pageSize).",$pageSize");

		$total_num=Db::query("select count(id) as sum from option_type where 1".$condition);

		return json(['code' => 1, 'data' => $list,'total_num'=>$total_num[0]['sum']]);
	}

	function del() {
		$input = input();

		if (!$input['id']) return json(['code' => 0, 'msg' => '数据错误']);

		$user = Db::table('option_type')->where('id', $input['id'])->find();

		if (empty($user)) return json(['code' => 0, 'msg' => '数据不存在']);

		$re = Db::name('option_type')->where('id', $input['id'])->delete();

		if (!$re) {
			return json(['code' => 0, 'msg' => '删除失败']);
		}
		return json(['code' => 1, 'msg' => '删除成功']);
	}

}